﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;

namespace ConsoleApplication1
{
    class Program
    {
    //    static string issuername = "owner";
    //    static string issuersecret = "lWHABJLYcc8kpoc8aeScYWN0I9hYs0n8q6FbsDORZk=";

        static string connectionstring;
        static string name = "test";

        private static NamespaceManager nspace;
        private static MessagingFactory msgfactory;

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Connection String of the Service Bus");
            getcs();

            nspace = NamespaceManager.CreateFromConfiguration(connectionstring);
            msgfactory = MessagingFactory.CreateFromConfiguration(connectionstring);

            Console.WriteLine("Creating queue 'OrdersService'...");

            if (nspace.QueueExists("OrdersService"))
                nspace.DeleteQueue("OrdersService");

            QueueDescription queue = nspace.CreateQueue("OrdersService");

            QueueClient client = msgfactory.CreateQueueClient(queue.Path, ReceiveMode.ReceiveAndDelete);

            Console.WriteLine("sending msg");
            send(client);
            receive();
            Console.ReadLine();
        }

        //getting the required connection string for the connection
        private static void getcs()
        {
            connectionstring = Console.ReadLine();

            if (connectionstring == null)
            {
                Console.WriteLine("please enter a valid Service Bus Connection String");
                getcs();
            }
        }
       
        //receiveing the message sent on the service bus
        private static void receive()
        {
            Console.Write("msg: " + MessagingFactory.CreateFromConfiguration().CreateQueueClient(name).Receive());
        }

        //sending the message
        private static void send(QueueClient qclient)
        {
            BrokeredMessage bm = new BrokeredMessage();
            bm.MessageId = Guid.NewGuid().ToString();
            bm.SessionId = Guid.NewGuid().ToString();
            qclient.Send(bm);

        }

        //initialization of the Namespace Manager and the Messaging Factory
        private static void setup()
        {
           nspace = NamespaceManager.CreateFromConfiguration(connectionstring);
           msgfactory = MessagingFactory.CreateFromConfiguration(connectionstring);

            QueueDescription qdesc = new QueueDescription(name);

            if (nspace.QueueExists(name))
            {
                nspace.DeleteQueue(name);
            }

            nspace.CreateQueue(qdesc);
        }
    }
}
